<template>
  <a-modal
    v-model:visible="visible"
    @close="close"
    :title="record.title"
    class="modal-dialog-wrapper"
    unmount-on-close
    :mask-closable="false"
    width="45vw"
    popup-container="body"
  >
    <div class="main">
      <!-- eslint-disable-next-line vue/no-v-html -->
      <div class="content" v-html="msgContent"></div>
      <!-- 操作按钮 -->
      <a-button
        v-if="record.type !== 9 && record.type !== 10"
        v-permission="isInfoPermission(record)"
        type="primary"
        @click="handleDetail(record)"
        >查看详情</a-button
      >
    </div>
    <template #footer>
      <a-space>
        <a-button @click="close">关闭</a-button>
        <a-button type="primary" v-if="record.nextId" @click="handleNext">下一条({{ record.unreadCount || 0 }}条)</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref } from 'vue'
  import { getMsgDetail, readMsg } from '@/api/common'
  import useInfoPermission from '@/hooks/useInfoPermission'
  const { isInfoPermission, toInfoDetail } = useInfoPermission()
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()
  const visible = ref(false)

  const open = (id) => {
    getDetail(id)
  }
  // 关闭
  const close = () => {
    visible.value = false
  }

  // 调用接口获取消息详情
  const record = ref({})
  const msgContent = ref('')
  const getDetail = (id) => {
    getMsgDetail({ id, status: 0 }).then((res) => {
      // 判断接口返回的状态码
      if (res.code === 200) {
        // 将返回的数据赋值给record
        record.value = res.result
        msgContent.value = res.result.content.replaceAll('\n', '<div style="height: 16px"></div>')
        visible.value = true
        // 已读、更新未读消息数量
        readMsg({ id: id }).then(() => {
          userStore.updateUnreadMsgCount()
        })
      }
    })
  }

  // 查看详情、（去处理消息）
  const handleDetail = (data) => {
    close()
    toInfoDetail(data)
  }

  // 下一条
  const handleNext = () => {
    getDetail(record.value.nextId)
  }

  defineExpose({ open })
</script>

<style lang="less" scoped>
  .main {
    min-height: 248px;
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    line-height: 22px;
    .content {
      margin-bottom: 12px;
    }
  }
</style>
